package messageMeTransfer.connection;

import java.io.IOException;
import java.net.ServerSocket;
import java.util.ArrayList;
import java.util.List;

import messageMeTransfer.interfaces.IConnectionListener;
import messageMeTransfer.interfaces.IPackage;
import messageMeTransfer.utilities.Client;
import messageMeTransfer.utilities.ClientConnectionReciever;

public class ServerConnection implements IConnectionListener {

	private int PORT = 4489;
	private ServerSocket socket = null;

	private List<Client> connectedClients = null;

	public ServerConnection() {
		this.establishConnection();
		this.enableConnectionReciever();
	}

	public void send(IPackage iPackage, Client client) {
		client.sendPackage(iPackage);
	}

	// Hilfsklasse um den aktuellen Client zu bekommen von dem das aktuell
	// abzuarbeitende Paket stammt.
	public Client getCurrentClient() {
		return this.connectedClients.get(0);
	}

	public IPackage recieve() {
		// TODO: Hier werden bisher nur die Pakete vom ersten Client
		// verarbeitet!
		IPackage iPackage = this.connectedClients.get(0).recievedPackages
				.firstElement();
		if (iPackage != null)
			this.connectedClients.get(0).recievedPackages.remove(iPackage);
		return iPackage;
	}

	private void establishConnection() {
		try {
			this.socket = new ServerSocket(this.PORT);
			this.connectedClients = new ArrayList<Client>();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void enableConnectionReciever() {
		ClientConnectionReciever reciever = new ClientConnectionReciever(
				this.socket);
		reciever.addListener(this);
		reciever.start();
	}

	private void closeConnection() {
		try {
			this.socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void connectionRecieved(Client client) {
		this.connectedClients.add(client);
	}
}
